package com.san.common.auth.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.san.common.auth.dao.UserDao;
import com.san.common.auth.entity.SysUser;
import com.san.common.auth.exception.NotFoundException;
import com.san.common.auth.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    UserService userService;


    @Override
    public Optional<SysUser> getUserByEmail(String email) {
        return userDao.selectByEmail(email);
    }

    @Override
    public Optional<SysUser> getUserByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    @Override
    public SysUser getUserByEmailNotNull(String email) {
        return getUserByEmail(email).orElseThrow(() -> new NotFoundException("The email does not exist").setErrorData(email));
    }

    @Override
    public SysUser getUserByUsernameNotNull(String username) {
        return getUserByUsername(username).orElseThrow(() -> new NotFoundException("The username does not exist").setErrorData(username));
    }

    @Override
    public boolean passwordMatch(SysUser sysUser, String plainPassword) {
        Assert.notNull(sysUser, "SysUser must not be null");

        return !StringUtils.isBlank(plainPassword) && BCrypt.checkpw(plainPassword, sysUser.getPassword());
    }

    @Override
    public boolean useMFA(Integer mfaType) {
        return mfaType != null && 0 != mfaType;
    }
}
